﻿using Lidgren.Network;
using NetBrick.Server;
using UniBrickCommon;
using UniBrickCommon.Packets;
using UniBrickServer.Utils;
using UnityEngine;

namespace UniBrickServer.Handler
{
    public class UpdateHandler : PacketHandler
    {
        public UpdateHandler(Server server) : base(server)
        {
        }

        public override void Process(object packetData, BasePeer sender)
        {
            var peer = (UniBrickPeer) sender;
            if (!peer.Authenticated)
            {
                peer.Kick("Cannot send update before authenticating.");
            }
            var updatePacket = (UpdatePacket.Request) packetData;
            if (!ValidMove(peer.Position, updatePacket.Position.ToVector()))
            {
                peer.Kick("Invalid movement.");
            }

            Log.Info("Old Pos: " + peer.Position);
            Log.Info("Old Rot: " + peer.Rotation);
            peer.Position = updatePacket.Position.ToVector();
            peer.Rotation = updatePacket.Rotation.ToQuaternion();
            Log.Info("New Pos: " + peer.Position);
            Log.Info("New Rot: " + peer.Rotation);

            var broadcastedUpdate = new UpdatePacket.Event(peer.Name, peer.Position.ToVectorString(), peer.Rotation.ToQuaternionString());
            UniBrickServer.Instance.BroadcastPacketToAuthenticated(UniBrickPacketCode.UpdateEvent, broadcastedUpdate,
                NetDeliveryMethod.UnreliableSequenced);
        }

        private static bool ValidMove(Vector3 originalPos, Vector3 newPos)
        {
            return true;
            //return Vector3.Distance(originalPos, newPos) < 20;
        }
    }
}